import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 2019/7/23 14:07 by 刘赵强
 * cas的三个缺点
 * 1.可能消耗性能 自旋锁（do while循环可能会循环很久)
 * 2.只能保证一个共享变量的原子性
 * 3.ABA问题
 *
 * AtomicReference可以将自定义的类包装成一个原子类
 **/
public class CAS {

    public static void main(String[] args) {
        User zs = new User("zs",22);
        User ls = new User("ls",33);

        AtomicReference atomicReference = new AtomicReference();
        atomicReference.set(zs);
        /**
         * 运行结果：
         * true    	CAS.User(userName=ls, age=33)
         * false	CAS.User(userName=ls, age=33)
         */
        System.out.println(atomicReference.compareAndSet(zs,ls)+"\t"+atomicReference.get());
        System.out.println(atomicReference.compareAndSet(zs,ls)+"\t"+atomicReference.get());
    }

    @Data
    @AllArgsConstructor
    static class User{
        String userName;
        Integer age;
    }
}

